//
//  YBShareView.m
//  WuyouTang
//
//  Created by YB007 on 2019/8/29.
//  Copyright © 2019 cat. All rights reserved.
//

#import "YBShareView.h"
#import "YBShareViewCell.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <AFNetworking.h>

typedef NS_ENUM(NSInteger,RKDownType) {
    RKDownType_Save,    //普通下载
    RKDownType_Chorus,  //合拍下载
};

@interface YBShareView()<UIGestureRecognizerDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
{
    BOOL _isDownLoading;
    MBProgressHUD *hud;
     NSURL *fullPathsss;
    
    NSArray *_shareArray;
    NSArray *_shareTitleArray;
    NSArray *_fucArray;
    NSArray *_funTitleArray;
    RKShareType _fromType;
    NSDictionary *_parameterDic;
}
@end
static YBShareView *_noShareUIManager = nil;
@implementation YBShareView


- (void)awakeFromNib {
    [super awakeFromNib];
 
    self.frame = [UIScreen mainScreen].bounds;
}

#pragma mark - 分享显示-底部
+(instancetype)showShareWithType:(RKShareType)fromType parameter:(NSDictionary *)parameter commplete:(ShareBlock)complete {
    YBShareView *sV = [[[NSBundle mainBundle]loadNibNamed:@"YBShareView" owner:nil options:nil]objectAtIndex:0];;
    
    if (complete) {
        sV.shareEvent = ^(int codeEvent,NSString *nums) {
            complete(codeEvent,nums);
        };
    }
    [sV setUpView:fromType parameter:parameter];
    
    return sV;
}
-(void)bottomViewParaInit {
    self.midBgView.hidden = YES;
    _isDownLoading = NO;
    _bgViewHeight.constant = 270+ShowDiff;
    _shareCollectionHeight.constant = 110;
    _fucCollectionHeight.constant = 110;
    self.frame = [UIScreen mainScreen].bounds;
    
    _titleL.text = YZMsg(@"分享至");
    
    _shareCollectionView.delegate = self;
    _shareCollectionView.dataSource = self;
    
    _fucCollectionView.delegate = self;
    _fucCollectionView.dataSource = self;
    
    [_shareCollectionView registerNib:[UINib nibWithNibName:@"YBShareViewCell" bundle:nil] forCellWithReuseIdentifier:@"ShareTypeCell"];
    [_fucCollectionView registerNib:[UINib nibWithNibName:@"YBShareViewCell" bundle:nil] forCellWithReuseIdentifier:@"SharefucCell"];
}
-(void)setUpView:(RKShareType)fromType parameter:(NSDictionary *)parameter{
    [self bottomViewParaInit];
    _fromType = fromType;
    _parameterDic = parameter;
    self.bgView.backgroundColor = self.shareCollectionView.backgroundColor = self.fucCollectionView.backgroundColor = (_fromType == RKShareType_Invite||_fromType == RKShareType_Liveing ||fromType == RKShareType_card)?[UIColor whiteColor] : Normal_Color;
    
    UITapGestureRecognizer *tagGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)];
    tagGes.delegate = self;
    [self addGestureRecognizer:tagGes];
    
    NSArray *shareA = [NSArray arrayWithArray:[common share_type]];
    NSMutableArray *m_arr = [NSMutableArray array];
    for (NSString *share_title in shareA) {
        NSString *show_title;
        if ([share_title isEqual:@"wx"]) {
            show_title = YZMsg(@"微信");
        }else if ([share_title isEqual:@"wchat"]){
            show_title = YZMsg(@"朋友圈");
        }else if ([share_title isEqual:@"qzone"]){
            show_title = YZMsg(@"QQ空间");
        }else if ([share_title isEqual:@"qq"]){
            show_title = @"QQ";
        }else if ([share_title isEqual:@"facebook"]){
            show_title = @"Facebook";
        }else if ([share_title isEqual:@"twitter"]){
            show_title = YZMsg(@"推特");
        }
        [m_arr addObject:show_title];
    }
    _shareArray = [NSArray arrayWithArray:shareA];
    _shareTitleArray = [NSArray arrayWithArray:m_arr];
    //fromType 0:视频界面分享 1:三级分销分享 2:直播主播预览界面分享(无UI) 3直播中分享 4发布界面分享(无UI)
    if (fromType == RKShareType_LookVdieo) {
        //视频
        /*
        _fucArray = @[@"举报",@"复制链接",@"合拍",@"保存",@"上热门"];
        _funTitleArray = @[YZMsg(@"举报"),YZMsg(@"复制链接"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"上热门")];
        NSString *ID = [NSString stringWithFormat:@"%@",[[_parameterDic valueForKey:@"userinfo"] valueForKey:@"id"]];
        if ([ID isEqual:[Config getOwnID]]) {
            _fucArray = @[@"删除",@"复制链接",@"合拍",@"保存",@"上热门"];
            _funTitleArray = @[YZMsg(@"删除"),YZMsg(@"复制链接"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"上热门")];
        }
        */
        [self lookVideoSubsWithColTitle:@"收藏"];
        
    }else if(fromType == RKShareType_Invite ) {
       //分销
        _fucArray = @[@"复制"];
        _funTitleArray = @[YZMsg(@"复制")];
    }else if (fromType == RKShareType_Liveing){
        //直播中
        _fucArray = @[];
        _funTitleArray = @[];
    }else if (fromType == RKShareType_card){
        //名片分享
        _fucArray = @[];
        _funTitleArray = @[];
    }
    if (fromType == RKShareType_LivePre){
        _titleL.textAlignment = NSTextAlignmentCenter;
        _closeBtn.hidden = YES;
    }
    
    if (_shareArray.count<=0) {
        _shareCollectionHeight.constant = 0;
        _bgViewHeight.constant -= 110;
    }
    if (_fucArray.count<=0) {
        _fucCollectionHeight.constant = 0;
        _bgViewHeight.constant -= 110;
    }
    /*
    if (_shareArray.count>4||_fucArray.count>4) {
        _titleL.text = YZMsg(@"分享至(左右滑动显示更多)");
    }
    */
    if (_shareArray.count>0||_fucArray.count>0) {
        [self showBottomView];
    }else {
       [MBProgressHUD showError:YZMsg(@"分享未开启")];
    }
}
-(void)lookVideoSubsWithColTitle:(NSString *)colTitle {
    _fucArray = @[@"上热门",colTitle,@"举报",@"合拍",@"保存",@"复制链接"];
    _funTitleArray = @[YZMsg(@"上热门"),YZMsg(colTitle),YZMsg(@"举报"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
    
    if ([PublicObj isUp]) {
        _fucArray = @[colTitle,@"举报",@"合拍",@"保存",@"复制链接"];
        _funTitleArray = @[YZMsg(colTitle),YZMsg(@"举报"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
    }
    
    NSString *ID = [NSString stringWithFormat:@"%@",[[_parameterDic valueForKey:@"userinfo"] valueForKey:@"id"]];
    if ([ID isEqual:[Config getOwnID]]) {
        _fucArray = @[@"上热门",colTitle,@"删除",@"合拍",@"保存",@"复制链接"];
        _funTitleArray = @[YZMsg(@"上热门"),YZMsg(colTitle),YZMsg(@"删除"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
        if ([PublicObj isUp]) {
            _fucArray = @[colTitle,@"删除",@"合拍",@"保存",@"复制链接"];
            _funTitleArray = @[YZMsg(colTitle),YZMsg(@"删除"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
        }
    }
}

- (void)setLimitDic:(NSDictionary *)limitDic{
    _limitDic = limitDic;
    int iscollection = [minstr([limitDic valueForKey:@"iscollection"]) intValue];
    if (iscollection == 1) {
        [self lookVideoSubsWithColTitle:@"已收藏"];
    }else{
        [self lookVideoSubsWithColTitle:@"收藏"];
    }
    [_fucCollectionView reloadData];
}

-(void)showBottomView {
    [_bgView layoutIfNeeded];
    [self layoutIfNeeded];
    UIBezierPath *maskPath ;
    maskPath = [UIBezierPath bezierPathWithRoundedRect:_bgView.bounds  byRoundingCorners:UIRectCornerTopRight|UIRectCornerTopLeft cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = _bgView.bounds;
    maskLayer.path = maskPath.CGPath;
    _bgView.layer.mask = maskLayer;
    _midBgView.hidden = YES;
    [[UIApplication sharedApplication].delegate.window addSubview:self];
    [UIView animateWithDuration:0.3 animations:^{
        
    } completion:^(BOOL finished) {
        self.backgroundColor = RGB_COLOR(@"#000000", 0.3);
    }];
}
#pragma mark - 无分享界面
+(instancetype)noShareUIManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _noShareUIManager = [[super allocWithZone:NULL]init];
    });
    return _noShareUIManager;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    return [self noShareUIManager];
}
-(void)executeShareWithType:(RKShareType)fromType shareType:(NSString *)shareType parameter:(NSDictionary *)parameter complete:(ShareBlock)complete {
    _fromType = fromType;
    _parameterDic = parameter;
    if (complete) {
        self.shareEvent = ^(int codeEvent, NSString *nums) {
            complete(codeEvent,nums);
        };
    }
    [self goShare:shareType];
}

- (IBAction)clickCancleBtn:(UIButton *)sender {
    [self dismiss];
}

#pragma mark - 有分享界面 (弹窗性质-中部)
+(instancetype)showMidPopShareType:(RKShareType)fromType parameter:(NSDictionary *)parameter commplete:(ShareBlock)complete;{
    YBShareView *sV = [[[NSBundle mainBundle]loadNibNamed:@"YBShareView" owner:nil options:nil]objectAtIndex:1];;
    if (complete) {
        sV.shareEvent = ^(int codeEvent,NSString *nums) {
            complete(codeEvent,nums);
        };
    }
    [sV setUpMidPopView:fromType parameter:parameter];
    return sV;
}
-(void)setUpMidPopView:(RKShareType)fromType parameter:(NSDictionary *)parameter{
    self.bgView.hidden = YES;
    
    _midDesL.text = YZMsg(@"作品已成功发布,可分享到:");
    _fromType = fromType;
    _parameterDic = parameter;
   
    NSArray *shareA = [NSArray arrayWithArray:[common share_type]];
    _shareArray = [NSArray arrayWithArray:shareA];
    //测试
    //_shareArray = @[@"wx",@"wchat",@"qzone",@"qq",@"wx",@"wchat",@"qzone",@"qq"];
    
    UIScrollView *shareScorllView = [[UIScrollView alloc]init];
    shareScorllView.showsHorizontalScrollIndicator = NO;
    shareScorllView.bounces = NO;
    [_midTypeBg addSubview:shareScorllView];
    shareScorllView.backgroundColor = UIColor.clearColor;
    [shareScorllView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.centerX.centerY.equalTo(_midTypeBg);
    }];
    
    CGFloat space = 20;
    int max_show_num = 4.0;
    CGFloat per_con_w = (_midBgView.width -space*(max_show_num+1))/max_show_num;
    CGFloat all_content_w = (_shareArray.count+1)*space+_shareArray.count*per_con_w;
    shareScorllView.contentSize = CGSizeMake(all_content_w, 0);
    
    UIView *scrollConten = [[UIView alloc]init];
    scrollConten.backgroundColor = UIColor.clearColor;
    [shareScorllView addSubview:scrollConten];
    [scrollConten mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(all_content_w);
        make.height.centerY.equalTo(shareScorllView);
        if (_shareArray.count<=4) {
            make.centerX.equalTo(shareScorllView);
        }else{
            make.left.equalTo(shareScorllView.mas_left).offset(0);
        }
    }];
    
    MASViewAttribute *mas_left = scrollConten.mas_left;
    for (int i=0; i<_shareArray.count; i++) {
        UIButton *btn = [UIButton buttonWithType:0];
        btn.tag = 1000 + i;
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"分享-%@",_shareArray[i]]] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(clickMidShare:) forControlEvents:UIControlEventTouchUpInside];
        [scrollConten addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(per_con_w);
            make.centerY.equalTo(scrollConten);
            make.left.equalTo(mas_left).offset(space);
        }];
        mas_left = btn.mas_right;
    }
    
    if (_shareArray.count>0) {
        [self showMidView];
    }else {
       [MBProgressHUD showError:YZMsg(@"分享未开启")];
    }
}
-(void)clickMidShare:(UIButton *)sender {
    int index = (int)sender.tag-1000;
    NSLog(@"mid===:%@",_shareArray[index]);
    [self goShare:_shareArray[index]];
}
-(void)showMidView {
    [[UIApplication sharedApplication].delegate.window addSubview:self];
    [UIView animateWithDuration:0.3 animations:^{
        
    } completion:^(BOOL finished) {
        self.backgroundColor = RGB_COLOR(@"#000000", 0.2);
    }];
}
- (IBAction)clickMidCancleBtn:(UIButton *)sender {
    [self dismiss];
}


#pragma mark - 公共
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    if ([touch.view isDescendantOfView:self.bgView] && _isDownLoading == NO) {
        return NO;
    }
    return YES;
}

-(void)dismiss {
    
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self removeFromSuperview];
}

#pragma mark - CollectionView 代理
/*
 * minimumLineSpacing、minimumInteritemSpacing去设置
 */
 -(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
     return CGSizeMake(_window_width/4,110);
 }
 -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
     return UIEdgeInsetsMake(0,0,0,0);
 }
 
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0.01;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.01;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == _shareCollectionView) {
        return _shareArray.count;
    }else {
        return _fucArray.count;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YBShareViewCell *cell;
    if (collectionView == _shareCollectionView) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ShareTypeCell" forIndexPath:indexPath];
        cell.thumbIV.image = [UIImage imageNamed:[NSString stringWithFormat:@"分享-%@",_shareArray[indexPath.row]]];
        cell.titleL.text = minstr(_shareTitleArray[indexPath.row]);
    }else if(collectionView == _fucCollectionView) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SharefucCell" forIndexPath:indexPath];
        cell.thumbIV.image = [UIImage imageNamed:[NSString stringWithFormat:@"分享-%@",_fucArray[indexPath.row]]];
        cell.titleL.text = minstr(_funTitleArray[indexPath.row]);
    }
    return cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == _shareCollectionView) {
        //分享显示在底部或者显示在中部
        NSLog(@"fenxiang");
        [self clickShareSender:(int)indexPath.row];
    }else {
        //方法点击
        NSLog(@"fuc");
        [self clickfucSender:(int)indexPath.row];
    }
}

#pragma mark - 分享事件
-(void)clickShareSender:(int)index {
    if (![minstr([_limitDic valueForKey:@"limit_status"]) isEqual:@"1"] && _fromType == RKShareType_LookVdieo) {
        [MBProgressHUD showError:YZMsg(@"该视频不能分享")];
        return;
    }
    NSString *eventStr = _shareArray[index];
    [self goShare:eventStr];
}
-(void)goShare:(NSString *)eventStr {
    if ([eventStr isEqual:@"wx"] || [eventStr isEqual:@"微信"]) {
        [self simplyShare:SSDKPlatformSubTypeWechatSession];
    }else if ([eventStr isEqual:@"wchat"] || [eventStr isEqual:@"朋友圈"]){
        [self simplyShare:SSDKPlatformSubTypeWechatTimeline];
    }else if ([eventStr isEqual:@"qzone"] || [eventStr isEqual:@"QQ空间"]){
        [self simplyShare:SSDKPlatformSubTypeQZone];
    }else if ([eventStr isEqual:@"qq"] || [eventStr isEqual:@"QQ"]){
        [self simplyShare:SSDKPlatformSubTypeQQFriend];
    }else if ([eventStr isEqual:@"facebook"] || [eventStr isEqual:@"Facebook"]){
        [self simplyShare:SSDKPlatformTypeFacebook];
    }else if ([eventStr isEqual:@"twitter"] || [eventStr isEqual:@"推特"]){
        [self simplyShare:SSDKPlatformTypeTwitter];
    }
}
- (void)simplyShare:(int)SSDKPlatformType {
    //fromType 0:视频界面分享 1:三级分销分享 2:直播主播预览界面分享(无UI) 3直播中分享 4发布界面分享(无UI)
    
    //默认分享视频
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    int SSDKContentType = SSDKContentTypeAuto;
    
    NSString *shareTitle = [common video_share_title];
    NSString *userNiceName = minstr([[_parameterDic valueForKey:@"userinfo"] valueForKey:@"user_nickname"]);
    if ([shareTitle containsString:@"{username}"]) {
        shareTitle = [shareTitle stringByReplacingOccurrencesOfString:@"{username}" withString:userNiceName];
    }
    
//    NSString *shareDes = [NSString stringWithFormat:@"%@%@",[[_parameterDic valueForKey:@"userinfo"] valueForKey:@"user_nickname"],[common video_share_des]];
    
    NSString *videoTitle = minstr([_parameterDic valueForKey:@"title"]);
    NSString *shareDes = [PublicObj checkNull:videoTitle] ? minstr([common video_share_des]):videoTitle;
    NSString *thumbStr = minstr([_parameterDic valueForKey:@"thumb_s"]);
    NSString *shareUrlStr = [h5url stringByAppendingFormat:@"/appapi/video/index?videoid=%@&type=0",[_parameterDic valueForKey:@"id"]];
    shareUrlStr = [shareUrlStr stringByAppendingFormat:@"&lang=%@",[YBLanguageTools serviceLang]];
    
    if (_fromType == RKShareType_Invite) {
        //三级分销分享
        shareDes = [common agent_share_des];
        thumbStr = [Config getUserAvatarThumb];
        shareUrlStr = [NSString stringWithFormat:@"%@/appapi/agentshare/index?uid=%@",h5url,[Config getOwnID]];
        shareUrlStr = [shareUrlStr stringByAppendingFormat:@"&lang=%@",[YBLanguageTools serviceLang]];
        shareTitle = [common agent_share_title];
    }
    if (_fromType == RKShareType_LivePre|| _fromType == RKShareType_Liveing) {
        //直播间分享、qq、都是下载链接
        //20-6-24微信改为观看
        shareUrlStr = minstr([common app_ios]);
        if (SSDKPlatformType == SSDKPlatformSubTypeWechatSession || SSDKPlatformType == SSDKPlatformSubTypeWechatTimeline) {
            shareUrlStr = [[common live_wx_siteurl] stringByAppendingFormat:@"%@",[_parameterDic valueForKey:@"hostId"]];
        }
        //shareDes = [NSString stringWithFormat:@"%@%@",[_parameterDic valueForKey:@"hostName"],[common live_share_des]];
        
        shareTitle = minstr([common live_share_title]);
        userNiceName = minstr([_parameterDic valueForKey:@"hostName"]);
        if ([shareTitle containsString:@"{username}"]) {
            shareTitle = [shareTitle stringByReplacingOccurrencesOfString:@"{username}" withString:userNiceName];
        }
        NSString *liveTitle = minstr([_parameterDic valueForKey:@"liveTitle"]);
        shareDes = [PublicObj checkNull:liveTitle] ? minstr([common live_share_des]):liveTitle;
    }
    if (_fromType == RKShareType_VideoPublish || _fromType == RKShareType_VPMidPop) {
        //发布界面分享
        shareDes = minstr([_parameterDic valueForKey:@"publish_des"]);
    }
    UIImage *shareImg;
    if (_fromType == RKShareType_card) {
        SSDKContentType = SSDKContentTypeImage;
        shareDes = minstr([_parameterDic valueForKey:@"shareTitle"]);
        shareUrlStr = minstr([_parameterDic valueForKey:@"href"]);
        NSData *imageData = [_parameterDic objectForKey:@"shareImage"];
        if (imageData) {
            shareImg = [[UIImage alloc] initWithData:imageData];

        }
//        shareImg = [_parameterDic valueForKey:@"shareImage"];
    }
    shareUrlStr = [shareUrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [shareParams SSDKSetupShareParamsByText:shareDes
                                     images:_fromType == RKShareType_card ? shareImg:thumbStr
                                        url:[NSURL URLWithString:shareUrlStr]
                                      title:shareTitle
                                       type:SSDKContentType];
    
    [shareParams SSDKEnableUseClientShare];
    
    YBWeakSelf;
    //进行分享
    [ShareSDK share:SSDKPlatformType
         parameters:shareParams
     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
         switch (state) {
             case SSDKResponseStateSuccess: {
                 [MBProgressHUD showSuccess:YZMsg(@"分享成功")];
                 if (_fromType == RKShareType_LookVdieo) {
                     [weakSelf addShare];
                 }
                 break;
             }
             case SSDKResponseStateFail: {
                 [MBProgressHUD showError:YZMsg(@"分享失败")];
                 break;
             }
             case SSDKResponseStateCancel: {
                 break;
             }
             default:
                 break;
         }
         if (_fromType != RKShareType_LookVdieo ) {
             [weakSelf dismiss];
         }
        if ((_fromType == RKShareType_LivePre || _fromType == RKShareType_VideoPublish || _fromType == RKShareType_VPMidPop) && weakSelf.shareEvent) {
            //2:直播预览分享、无论成功失败都去开始直播
            //4:发布页面分享、无论成功失败都返回首页
            weakSelf.shareEvent(6, @"");
        }
        if (_fromType == RKShareType_LivePre || _fromType == RKShareType_Liveing) {
            //每日任务-直播分享
            [[YBDayTaskManager shareInstance]taskOfShareRoom];
        }
     }];
}
-(void)addShare{
    
 NSString *random_str = [PublicObj stringToMD5:[NSString stringWithFormat:@"%@-%@-#2hgfk85cm23mk58vncsark",[Config getOwnID],[_parameterDic valueForKey:@"id"]]];
   NSString *url = [NSString stringWithFormat:@"Video.addShare&uid=%@&videoid=%@&random_str=%@",[Config getOwnID],[_parameterDic valueForKey:@"id"],random_str];
   YBWeakSelf;
   [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
       if (code == 0) {
           NSDictionary *infoDic = [info firstObject];
           if (weakSelf.shareEvent) {
               weakSelf.shareEvent(0, minstr([infoDic valueForKey:@"shares"]));
               [weakSelf dismiss];
           }
       }else{
           [MBProgressHUD showPop:msg];
       }
   } Fail:^(id fail) {
       
   }];
    
}

#pragma mark - 功能事件
-(void)clickfucSender:(int)index {
    //条件判断不需要翻译
    NSString *eventStr = _fucArray[index];
    if ([eventStr isEqual:@"举报"] && _fromType == RKShareType_LookVdieo) {
        if (self.shareEvent) {
            self.shareEvent(2, @"");
        }
        [self dismiss];
    }else if ([eventStr isEqual:@"复制链接"] && _fromType == RKShareType_LookVdieo) {
        if (![minstr([_limitDic valueForKey:@"limit_status"]) isEqual:@"1"]) {
            [MBProgressHUD showError:YZMsg(@"该视频不能复制链接")];
            return;
        }
        UIPasteboard *paste = [UIPasteboard generalPasteboard];
        if (![PublicObj checkNull:[_parameterDic valueForKey:@"href"]]) {
            NSString *href = [NSString stringWithFormat:@"%@",[_parameterDic valueForKey:@"href_w"]];
            if (href.length <= 0) {
                [MBProgressHUD showError:YZMsg(@"该视频暂不支持复制链接")];
                return;
            }
            href = [PublicObj decrypt:href];
            paste.string = href;
            [MBProgressHUD showSuccess:YZMsg(@"复制成功")];
        }
        [self dismiss];
    }else if ([eventStr isEqual:@"删除"] && _fromType == RKShareType_LookVdieo) {
        YBWeakSelf;
        NSDictionary *contentDic = @{@"title":YZMsg(@"提示"),@"msg":YZMsg(@"确认删除?"),@"left":YZMsg(@"取消"),@"right":YZMsg(@"确定")};
        [YBAlertView showAlertView:contentDic complete:^(int eventType) {
            if (eventType == 1) {
                [weakSelf delVideo];
            }else{
                [weakSelf dismiss];
            }
        }];
        self.hidden = YES;
    }else if ([eventStr isEqual:@"保存"] && _fromType == RKShareType_LookVdieo){
        if (![minstr([_limitDic valueForKey:@"limit_status"]) isEqual:@"1"]) {
            [MBProgressHUD showError:YZMsg(@"该视频不能保存")];
            return;
        }
        _isDownLoading = YES;
        [self downloadVideo:RKDownType_Save];
    }else if ([eventStr isEqual:@"复制"] && _fromType == RKShareType_Invite) {
        //三级分销
         NSString *copyStr = [NSString stringWithFormat:@"%@/appapi/agentshare/index?uid=%@",h5url,[Config getOwnID]];
        copyStr = [copyStr stringByAppendingFormat:@"&lang=%@",[YBLanguageTools serviceLang]];
        UIPasteboard *paste = [UIPasteboard generalPasteboard];
        paste.string = copyStr;
        [MBProgressHUD showError:YZMsg(@"复制成功")];
        [self dismiss];
    }else if ([eventStr isEqual:@"合拍"] && _fromType == RKShareType_LookVdieo) {
        if ([[Config getOwnID]intValue]<0) {
            [self dismiss];
            [PublicObj warnLogin];
            return;
        }
        if (![minstr([_limitDic valueForKey:@"video_status"]) isEqual:@"1"]) {
            [MBProgressHUD showError:minstr([_limitDic valueForKey:@"video_msg"])];
            return;
        }
        if (![minstr([_limitDic valueForKey:@"limit_status"]) isEqual:@"1"]) {
            [MBProgressHUD showError:YZMsg(@"该视频不能合拍")];
            return;
        }
        _isDownLoading = YES;
        [self downloadVideo:RKDownType_Chorus];
    }else if ([eventStr isEqual:@"上热门"] && _fromType == RKShareType_LookVdieo) {
        
        if (self.shareEvent) {
            self.shareEvent(5, @"");
        }
        [self dismiss];
    }else if ([eventStr isEqual:@"收藏"] && _fromType == RKShareType_LookVdieo) {
        if (self.shareEvent) {
            self.shareEvent(7, @"");
        }
        [self dismiss];
    }
    
}

-(void)delVideo {
    //[_parameterDic valueForKey:@"id"]
    NSDictionary *subdic = @{
                             @"uid":[Config getOwnID],
                             @"token":[Config getOwnToken],
                             @"videoid":[NSString stringWithFormat:@"%@",[_parameterDic valueForKey:@"id"]]
                             };
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Video.del" Dic:subdic Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            [MBProgressHUD showSuccess:YZMsg(@"删除成功")];
            if (weakSelf.shareEvent) {
                weakSelf.shareEvent(3, @"");
                [weakSelf dismiss];
            }
        }else{
            weakSelf.hidden = NO;
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        weakSelf.hidden = NO;
    }];
    
    
}


//下载视频到本地
-(void)downloadVideo:(RKDownType)downType{
    [self dismiss];
    NSString *href = [NSString stringWithFormat:@"%@",[_parameterDic valueForKey:@"href_w"]];
    if (downType == RKDownType_Chorus) {
        href = [NSString stringWithFormat:@"%@",[_parameterDic valueForKey:@"href"]];
    }
    href = [PublicObj decrypt:href];
    if (href.length <= 0 || [href containsString:@".m3u8"]) {
        if (downType == RKDownType_Save) {
            [MBProgressHUD showError:YZMsg(@"该视频暂不支持下载")];
        }else {
            [MBProgressHUD showError:YZMsg(@"该视频暂不支持合拍")];
        }
        _isDownLoading = NO;
        [self dismiss];
        return;
    }
    NSString *title = [NSString stringWithFormat:@"%@",[_parameterDic valueForKey:@"title"]];
    if (title.length == 0) {
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval a=[dat timeIntervalSince1970]*1000;
        NSString *timeString = [NSString stringWithFormat:@"%d", (int)a];
        title = timeString;
    }
    hud = [MBProgressHUD showHUDAddedTo:[YBBaseAppDelegate sharedAppDelegate].topViewController.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    NSString *showDesText = YZMsg(@"正在下载视频");
    downType == RKDownType_Save ? (showDesText = YZMsg(@"正在下载视频")):(showDesText = YZMsg(@"请稍等..."));
    hud.label.text = showDesText;
    //1.创建会话管理者
    //AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    NSURL *url = [NSURL URLWithString:href];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSMutableURLRequest *m_reques = [request mutableCopy];
    [m_reques addValue:h5url forHTTPHeaderField:@"referer"];
    request = [m_reques copy];
    NSURLSessionDownloadTask *download = [[WYNetworking ybnetManager] downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //hud.progress = downloadProgress.fractionCompleted;
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        });
        //监听下载进度
        //completedUnitCount 已经下载的数据大小
        //totalUnitCount     文件数据的中大小
        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        NSLog(@"targetPath:%@",targetPath);
        NSLog(@"fullPath:%@",fullPath);
        
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        fullPathsss = filePath;
        NSLog(@"%@",filePath);
        
        if (downType == RKDownType_Save) {
            UISaveVideoAtPathToSavedPhotosAlbum([filePath path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _isDownLoading = NO;
                [self dismiss];
                [MBProgressHUD hideHUDForView:[YBBaseAppDelegate sharedAppDelegate].topViewController.view animated:YES];
                if ([PublicObj checkNull:[fullPathsss path]]) {
                    [MBProgressHUD showPop:YZMsg(@"该视频暂不支持合拍")];
                    return ;
                }
                if (self.shareEvent) {
                    self.shareEvent(4, [fullPathsss path]);
                }
            });
        }
        
    }];
    
    //3.执行Task
    [download resume];
    
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo: (void *)contextInfo {
    if (error == nil) {
        NSLog(@"视频保存成功");
        hud.label.text = YZMsg(@"视频保存成功");
    }else{
        NSLog(@"视频保存失败");
        hud.label.text = YZMsg(@"频保存失败");
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:[YBBaseAppDelegate sharedAppDelegate].topViewController.view animated:YES];
        _isDownLoading = NO;
        [self dismiss];
    });
    BOOL isOk = [[NSFileManager defaultManager] removeItemAtPath:[fullPathsss path] error:nil];
    NSLog(@"%d",isOk);
}

@end
